package com.yj.auto.core.web.common.controller;

import java.io.File;
import java.util.List;

import javax.sql.DataSource;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import com.xiaoleilu.hutool.util.ZipUtil;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.plugin.generator.AutoGenerator;
import com.yj.auto.plugin.generator.AutoMetaBuilder;

@Controller(viewPath = "system")
public class GeneratorController extends BaseController {
	private static Log logger = Log.getLog(GeneratorController.class);

	public void index() {
		DataSource ds = DbKit.getConfig().getDataSource();
		AutoMetaBuilder amb = new AutoMetaBuilder(ds);
		List<TableMeta> list = amb.build();
		setAttr("result", list);
		render("table_index.html");
	}

	public void detail() {
		String name = getPara();
		TableMeta model = null;
		if (StrKit.notBlank(name)) {
			DataSource ds = DbKit.getConfig().getDataSource();
			AutoMetaBuilder amb = new AutoMetaBuilder(ds);
			List<TableMeta> list = amb.build(name);
			if (list.size() > 0) {
				model = list.get(0);
			}
		}
		setAttr("model", model);
		render("table_detail.html");
	}

	public void build() throws Exception {
		String[] tables = getPara("tables").split(",");
		String tableRemovePrefixes = getPara("prefixes");
		String viewPath = getPara("viewPath");
		String basepackage = getPara("basepackage");
		basepackage = getPara("basepackage");
		AutoGenerator gen = new AutoGenerator(tableRemovePrefixes, viewPath, basepackage, DbKit.getConfig().getDataSource());
		gen.generate(tables);
		File zip = ZipUtil.zip(new File(gen.getTargetPath()));
		renderFile(zip);
	}
}